package en.edu.zucc.pb.loginapplication.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import lombok.Data;

/**
 * https://www.jb51.net/article/158640.htm
 */
@Data
public class PicUtil {

    Context context;
    ImageView imageView;

    public PicUtil(Context context, ImageView imageView) {
        this.context = context;
        this.imageView = imageView;
//        init();
    }

    private static final String TAG = "PicUtil";

//    @TargetApi(19)
    public void putPic( Uri uri ){
//        点击了 就选中了一个 图片
        String imagePath = null;
//        Uri uri = data.getData();
//        调试怎么没有中断
//        I/PicUtil: uri: content://media/external/images/media
        Log.i(TAG,"uri: "+uri);
        if (DocumentsContract.isDocumentUri(context,uri)){
            //如果document类型是U日，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            Log.i(TAG,"docId: "+docId);
//            不是这个
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];//解析出数字格式id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }
            Log.i(TAG,"imagePath: "+imagePath);
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果是普通类型 用普通方法处理
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            //如果file类型位uri直街获取图片路径即可
            imagePath = uri.getPath();
        }
        Log.i(TAG,"imagePath: "+imagePath);
        displayImage(imagePath);
    }

    @TargetApi(19)
    private void handleImageOmKitKat(Intent data){
//        点击了 就选中了一个 图片
        String imagePath = null;
        Uri uri = data.getData();
//        调试怎么没有中断
//        I/PicUtil: uri: content://media/external/images/media
        Log.i(TAG,"uri: "+uri);
        if (DocumentsContract.isDocumentUri(context,uri)){
            //如果document类型是U日，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            Log.i(TAG,"docId: "+docId);
//            不是这个
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];//解析出数字格式id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }
            Log.i(TAG,"imagePath: "+imagePath);
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果是普通类型 用普通方法处理
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            //如果file类型位uri直街获取图片路径即可
            imagePath = uri.getPath();
        }
        Log.i(TAG,"imagePath: "+imagePath);
        displayImage(imagePath);
    }

//    kitkat是Google（谷歌公司）Android 4.4（安卓系统）的代号。
    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        //通过Uri和selection来获取真实图片路径
//        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null){
            if (cursor.moveToFirst()){
//                弄到的是第一张图片吧  怎么根据选择的。。
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void displayImage(String imagePath){

        displayImage(imageView,imagePath);
    }

    public  void displayImage(ImageView imageView,String imagePath){
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            imageView01.setImageBitmap(bitmap);
//            imageView.set
            imageView.setImageBitmap(bitmap);
        }else {
//            Toast.makeText(MainActivity.this,"fail to get image",Toast.LENGTH_SHORT).show();
            Toast.makeText(context,"fail to get image",Toast.LENGTH_SHORT).show();
        }
    }


    public  void init(){
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Activity activity=    (Activity) context;
                if(ContextCompat.checkSelfPermission(context,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(activity,new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },1);
//                    申请权限
                }
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                activity.   startActivityForResult(intent, IMAGE_REQUEST_CODE);
                handleImageOmKitKat(intent);
//                这里直接贴上了
//                这里怎么得到图片啊
//                chnage();
            }
        });
//        chnage();
    }



    //从相册获得图片
    Bitmap bitmap;
    //判断返回到的Activity
    private static final int IMAGE_REQUEST_CODE = 0;
    //图片路径
    private String path ;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if((Integer)msg.obj==0){
//                imageView01.setImageBitmap(bitmap);
                imageView.setImageBitmap(bitmap);
            }
            super.handleMessage(msg);
        }
    };




//    https://www.jb51.net/article/158640.htm
    /*定义一个Handler，定义延时执行的行为*/
    public void chnage(){
        new Thread(){
            @Override
            public void run() {
                while ( bitmap == null ){
//                    这个path 哪里来的
                    bitmap = BitmapFactory.decodeFile(path);
                    Log.v("qwe","123");
                }
                Message message = handler.obtainMessage();
                message.obj = 0;
                handler.sendMessage(message);
            }
        }.start();
    }




}
